<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <!-- 网站图标 -->
   <link rel="shortcut icon" href="../photo/网站.png" type="image/x-icon">
   <title>五育系统学生端</title>
  <link rel="stylesheet" href="../css/ShowTrend.css">
  <!-- 引入 Vue.js -->
  <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
  <script src="../js/untils/request.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <!-- 引入 Element UI CSS -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <!-- 引入 Element UI JS -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <script src="../js/untils/request.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
  <script src="../js/showTrend.js"></script>

</head>

<body>
  <div id="main">
    <div id="click-section">
      <div id="drawerboxes">
        <div class="drawerbox active">
          <button class="drawer-btn active" @click="slideTo(1)">综合发展趋势<span class="drawer-head">1</span></button>
        </div>
        <div class="drawerbox">
          <button class="drawer-btn" @click="slideTo(2)">德育发展<span class="drawer-head">2</span></button>
        </div>
        <div class="drawerbox">
          <button class="drawer-btn" @click="slideTo(3)">智育发展<span class="drawer-head">3</span></button>
        </div>
        <div class="drawerbox">
          <button class="drawer-btn" @click="slideTo(4)">体育发展<span class="drawer-head">4</span></button>
        </div>
        <div class="drawerbox">
          <button class="drawer-btn" @click="slideTo(5)">美育发展<span class="drawer-head">5</span></button>
        </div>
        <div class="drawerbox">
          <button class="drawer-btn" @click="slideTo(6)">劳育发展<span class="drawer-head">6</span></button>
        </div>
      </div>
    </div>
    <div id="slide-section">
      <div id="slide-bar">
        <div id="bar"></div>
      </div>
      <div id="card-section">
        <!-- 整体 -->
        <div id="card1" class="card">
          <div class="card-small-title">欢迎查看{{SartTime}}至{{EndTime}}发展趋势报告</div>
          <div class="card-title">综合发展报告</div>
          <div class="card-content">
            在整个五育评价过程中，五育评价的结果可能受到多方面因素的影响，请同学们客观对待
          </div>
          <div class="card-content">
            <canvas id="cardEchartsTotal" width="80" height="30"></canvas>
            <div class="text">
              <p>📚 {{TotalContent.performanceLevels}}</p>
              <p>📚 整体上体现{{TotalContent.trend}}</p>
              <p>📚 {{TotalContent.overallPerformance}}</p>
            </div>
          </div>
        </div>
        <!-- 德育 -->
        <div id="card2" class="card">
          <div class="card-small-title">欢迎查看{{SartTime}}至{{EndTime}}发展趋势报告</div>
          <div class="card-title">德育发展报告</div>
          <div class="card-content">
            <canvas id="cardEchartsDY" width="80" height="30"></canvas>
            <div class="text">
              <p>📚 {{Content1.performanceLevels}}</p>
              <p>📚 整体上体现{{Content1.trend}}</p>
              <p>📚 {{Content1.overallPerformance}}</p>
            </div>
          </div>
        </div>
        <!-- 智育 -->
        <div id="card3" class="card">
          <div class="card-small-title">欢迎查看{{SartTime}}至{{EndTime}}发展趋势报告</div>
          <div class="card-title">智育发展报告</div>
          <div class="card-content">
            <canvas id="cardEchartsZY" width="80" height="30"></canvas>
            <div class="text">
              <p>📚 {{Content2.performanceLevels}}</p>
              <p>📚 整体上体现{{Content2.trend}}</p>
              <p>📚 {{Content2.overallPerformance}}</p>
            </div>
          </div>
        </div>
        <!-- 体 -->
        <div id="card4" class="card">
          <div class="card-small-title">欢迎查看{{SartTime}}至{{EndTime}}发展趋势报告</div>
          <div class="card-title">体育发展报告</div>
          <div class="card-content">
            <canvas id="cardEchartsTY" width="80" height="30"></canvas>
            <div class="text">
              <p>📚 {{Content3.performanceLevels}}</p>
              <p>📚 整体上体现{{Content3.trend}}</p>
              <p>📚 {{Content3.overallPerformance}}</p>
            </div>
          </div>
        </div>
        <!-- 美 -->
        <div id="card5" class="card">
          <div class="card-small-title">欢迎查看{{SartTime}}至{{EndTime}}发展趋势报告</div>
          <div class="card-title">美育发展报告</div>
          <div class="card-content">
            <canvas id="cardEchartsMY" width="80" height="30"></canvas>
            <div class="text">
              <p>📚 {{Content4.performanceLevels}}</p>
              <p>📚 整体上体现{{Content4.trend}}</p>
              <p>📚 {{Content4.overallPerformance}}</p>
            </div>
          </div>
        </div>
        <!-- 劳 -->
        <div id="card6" class="card">
          <div class="card-small-title">欢迎查看{{SartTime}}至{{EndTime}}发展趋势报告</div>
          <div class="card-title">劳育发展报告</div>
          <div class="card-content">
            <canvas id="cardEchartsLY" width="80" height="30"></canvas>
            <div class="text">
              <p>📚 {{Content5.performanceLevels}}</p>
              <p>📚 整体上体现{{Content5.trend}}</p>
              <p>📚 {{Content5.overallPerformance}}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script type="module">
    const httpService = new HttpService('http://60.205.234.107:7512');
    // const httpService = new HttpService('http:localhost:8080');

    // 用vue语法
    new Vue({
      el: '#main',
      data() {
        return {
          chosenSlideNumber: 1, // 当前选择的幻灯片编号 
          offset: 0,// 幻灯片偏移量 
          barOffset: 0, // 导航条偏移量 
          intervalID: 0, // 定时器 ID 
          SartTime: '',
          EndTime: '',
          StudentId: "",
          // 该同学的数据
          studentData: [],
          dateList: [],
          // 处理后的每月的数据
          combinedScores: [],

          //文本信息
          TotalContent: {
            performanceLevels: "",
            slope: null,
            trend: "",
            average: null,
            overallPerformance: ""
          },
          Content1: {},
          Content2: {},
          Content3: {},
          Content4: {},
          Content5: {},

          // 评价信息
          Evaluation: {},
          // 获取身份信息
          studentInfo: {
            scchoolMeaasge: "",
            studentclass: "",
            StudentId: "",
            yearAdmission: "",
            Yearstem: ""
          }
        }
      },
      methods: {
        /** 1. 启动幻灯片轮播 */
        // 1.1 启动幻灯片轮播 
        startSlide() {
          this.intervalID = setInterval(() => {
            this.slideTo(this.chosenSlideNumber % 5 + 1); // 每次切换到下一个幻灯片 
          }, 3000); // 每隔 3 秒自动切换幻灯片 
        },
        // 1.2 切换到指定编号的幻灯片 
        slideTo(slideNumber) {
          this.drawerboxToggle(slideNumber); // 切换抽屉面板状态 
          this.drawerbtnToggle(slideNumber); // 切换抽屉按钮状态 
          // 更新偏移量 
          let previousSlideNumber = this.chosenSlideNumber;
          this.chosenSlideNumber = slideNumber;
          this.offset += (this.chosenSlideNumber - previousSlideNumber) * (-100); // 计算幻灯片偏移量 
          this.barOffset += (this.chosenSlideNumber - previousSlideNumber) * (100); // 计算导航条偏移量 
          this.barSlide(this.barOffset); // 移动导航条 
          // 获取所有幻灯片，为每个幻灯片设置偏移量 
          const slides = document.querySelectorAll(".card");
          Array.from(slides).forEach(slide => {
            slide.style.transform = `translateY(${this.offset}%)`;
          })
        },
        // 1.3 切换抽屉面板状态 
        drawerboxToggle(drawerboxNumber) {
          let prevDrawerboxNumber = this.chosenSlideNumber;
          const drawerboxes = document.querySelectorAll(".drawerbox");
          drawerboxes[prevDrawerboxNumber - 1].classList.toggle("active"); // 切换前一个抽屉面板的状态 
          drawerboxes[drawerboxNumber - 1].classList.toggle("active"); // 切换当前抽屉面板的状态 
        },
        // 1.4 切换抽屉按钮状态 
        drawerbtnToggle(drawerBtnNumber) {
          let prevDrawerBtnNumber = this.chosenSlideNumber;
          const drawerBtns = document.querySelectorAll(".drawer-btn");
          drawerBtns[prevDrawerBtnNumber - 1].classList.toggle("active"); // 切换前一个抽屉按钮的状态 
          drawerBtns[drawerBtnNumber - 1].classList.toggle("active"); // 切换当前抽屉按钮的状态 
        },
        // 1.5 移动导航条 
        barSlide(barOffset) {
          const bar = document.querySelector("#bar");
          bar.style.transform = `translateY(${this.barOffset}%)`;
        },
        /**
         * self方法
         * 处理学生数据
         */
        async getTermDates(startYear, gradeTerm) {
          // 解析学年和学期
          const regex = /(\d+)年级(上学期|下学期)/;
          const match = gradeTerm.match(regex);

          if (!match) {
            return null; // 格式错误
          }

          const grade = parseInt(match[1]); // 获取年级
          const term = match[2]; // 获取学期（上学期或下学期）
          // 根据入学年份和年级推算当前学年的年份
          const schoolYear = startYear + grade - 1; // 学年从入学年份开始

          let startMonth, endMonth;

          // 根据学期推算起始和结束月份
          if (term === "上学期") {
            // 上学期：从 9月 到 1月
            startMonth = 9;
            endMonth = 1; // 上学期通常到第二年1月结束
          } else if (term === "下学期") {
            // 下学期：从 3月 到 6月
            startMonth = 3;
            endMonth = 6;
          }

          const startDateYear = startMonth === 9 ? schoolYear : schoolYear + 1;
          const endDateYear = endMonth === 1 ? schoolYear + 1 : schoolYear;

          // 拼接日期，确保月份为两位数
          const startDate = `${startDateYear}-${String(startMonth).padStart(2, '0')}`;
          const endDate = `${endDateYear}-${String(endMonth).padStart(2, '0')}`;

          return {
            startDate,
            endDate
          };
        },
        async getStudnetScore() {
          const sid = this.studentInfo.StudentId;
          const result = await this.getTermDates(parseInt(this.studentInfo.yearAdmission), this.studentInfo.Yearstem);
          const List = [];

          try {
            const res = await httpService.get(`/studentstandardscores/studentstandardscores/list/${sid}`);
            if (res.code === 200) {
              res.data.forEach(element => {
                console.log(element);
                if (element.calculationtime.slice(0, 7) >= result.startDate && element.calculationtime.slice(0, 7) <= result.endDate) {
                  List.push(element);
                }
              });
              // 数据加载完成后再执行下面的操作
              this.studentData = List;
              this.handledigital();
              this.handleTime(List);
            } else {
              console.error('Error fetching data:', res.message);
            }
          } catch (error) {
            console.error('Error:', error);
          }
        },

        // 处理时间的函数
        handleTime(res) {
          res.forEach(element => {
            // 提取年月信息
            const yearMonth = new Date(element.calculationtime).toISOString().slice(0, 7); // 'YYYY-MM'
            this.dateList.push(yearMonth);
          });

          // 找出最大和最小年月
          const uniqueMonths = [...new Set(this.dateList)]; // 去重
          this.dateList = uniqueMonths.sort(); // 排序
          const startTime = this.dateList[0]; // 最小年月
          const endTime = this.dateList[this.dateList.length - 1]; // 最大年月
          this.SartTime = startTime;
          this.EndTime = endTime;
        },
        // 处理数据的函数
        handledigital() {
          // console.log(this.studentData);
          const combinedScores = this.studentData.reduce((acc, item) => {
            const scores = JSON.parse(item.strandScore);
            const yearMonth = item.calculationtime.slice(0, 7); // 提取年月

            acc[yearMonth] = {
              "1": scores["1"],
              "2": scores["2"],
              "3": scores["3"],
              "4": scores["4"],
              "5": scores["5"],
              "totalIndicator": scores["totalIndicator"]
            };

            return acc;
          }, {});

          this.combinedScores = combinedScores;
          // console.log("combinedScores", combinedScores);

          showTotal(combinedScores)
          showDY(combinedScores)
          showZY(combinedScores)
          showTY(combinedScores)
          showMY(combinedScores)
          showLY(combinedScores)
          this.dataAnalysisTotal(combinedScores)
          this.analyzeAllIndicators(combinedScores)
          // console.log(this.combinedScores);
        },
        /** 数据分析开始*/
        dataAnalysisTotal(data) {
          // 提取 totalIndicator 数据
          const totalIndicators = Object.keys(data).map(month => data[month].totalIndicator);
          const mouth = Object.keys(data).map(month => month);
          // console.log(mouth)

          // 提取动态分数界限
          const scoreRanges = this.evaluation.find(item => item.type === "totalIndicator").scoreRanges;
          // 提取动态分数界限
          const thresholds = scoreRanges.map(range => ({
            start: parseFloat(range.start),
            end: parseFloat(range.end),
            description: range.description
          }));

          // 使用动态值计算性能等级
          const performanceLevels = totalIndicators.map(score => {
            const level = thresholds.find(threshold => score >= threshold.start && score <= threshold.end);
            return level ? level.description : "未知"; // 如果没有找到匹配的等级，返回“未知”
          });
          // console.log(this.summarizePerformance(performanceLevels));
          // 计算趋势（斜率）
          const calculateSlope = (values) => {
            const n = values.length;
            const sumX = values.reduce((sum, _, index) => sum + index, 0);
            const sumY = values.reduce((sum, value) => sum + value, 0);
            const sumXY = values.reduce((sum, value, index) => sum + index * value, 0);
            const sumX2 = values.reduce((sum, _, index) => sum + index * index, 0);

            const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
            return slope;
          };

          const slope = calculateSlope(totalIndicators);

          // 计算平均值
          const average = totalIndicators.reduce((sum, value) => sum + value, 0) / totalIndicators.length;

          // 提取动态分数界限
          const overscoreRanges = this.evaluation.find(item => item.type === "individualIndicator").scoreRanges;
          // 确定整体表现
          let overallPerformance = "未知"; // 默认值
          for (const range of overscoreRanges) {
            if (average >= range.start && average <= range.end) {
              overallPerformance = range.description;
              break; // 找到匹配后退出循环
            }
          }

          // 输出结果
          // console.log("各月表现:", performanceLevels);
          // console.log("趋势斜率:", slope);
          // console.log("平均值:", average);
          // console.log("整体表现:", overallPerformance);

          this.TotalContent = {
            performanceLevels: this.summarizePerformance(performanceLevels, mouth),
            slope: slope,
            average: average,
            overallPerformance: overallPerformance,
            trend: slope > 0 ? "上升趋势" : "下降趋势"
          }
          // console.log(this.TotalContent)
        },
        dataAnalysis(data, indicatorKey) {
          const totalIndicators = Object.keys(data).map(month => data[month][indicatorKey]);
          const mouth = Object.keys(data).map(month => month);
          // 提取动态分数界限
          const scoreRanges = this.evaluation.find(item => item.type === "totalIndicator").scoreRanges;
          // 提取动态分数界限
          const thresholds = scoreRanges.map(range => ({
            start: parseFloat(range.start),
            end: parseFloat(range.end),
            description: range.description
          }));

          // 使用动态值计算性能等级
          const performanceLevels = totalIndicators.map(score => {
            const level = thresholds.find(threshold => score >= threshold.start && score <= threshold.end);
            return level ? level.description : "未知"; // 如果没有找到匹配的等级，返回“未知”
          });

          const calculateSlope = (values) => {
            const n = values.length;
            const sumX = values.reduce((sum, _, index) => sum + index, 0);
            const sumY = values.reduce((sum, value) => sum + value, 0);
            const sumXY = values.reduce((sum, value, index) => sum + index * value, 0);
            const sumX2 = values.reduce((sum, _, index) => sum + index * index, 0);
            const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
            return slope;
          };

          const slope = calculateSlope(totalIndicators);
          const average = totalIndicators.reduce((sum, value) => sum + value, 0) / totalIndicators.length;

          // 提取动态分数界限
          const overscoreRanges = this.evaluation.find(item => item.type === "individualIndicator").scoreRanges;
          // 确定整体表现
          let overallPerformance = "未知"; // 默认值
          for (const range of overscoreRanges) {
            if (average >= range.start && average <= range.end) {
              overallPerformance = range.description;
              break; // 找到匹配后退出循环
            }
          }
          return {
            performanceLevels: this.summarizePerformance(performanceLevels, mouth),
            slope: slope,
            average: average,
            overallPerformance: overallPerformance,
            trend: slope > 0 ? "上升趋势" : "下降趋势"
          };
        },
        // 用于分析不同指标的数据
        analyzeAllIndicators(data) {
          this.Content1 = this.dataAnalysis(data, "1");
          this.Content2 = this.dataAnalysis(data, "2");
          this.Content3 = this.dataAnalysis(data, "3");
          this.Content4 = this.dataAnalysis(data, "4");
          this.Content5 = this.dataAnalysis(data, "5");

          // console.log(this.Content1, this.Content2, this.Content3, this.Content4, this.Content5);
        },
        // 数据分析
        summarizePerformance(performanceLevels, monthLabels) {
          const levelChanges = [];
          let currentLevel = performanceLevels[0];
          let count = 1;
          let months = [monthLabels[0]]; // 存储当前阶段的月份

          // 遍历表现阶段，识别变化并计数
          for (let i = 1; i < performanceLevels.length; i++) {
            if (performanceLevels[i] === currentLevel) {
              count++;
              months.push(monthLabels[i]); // 记录当前阶段的月份
            } else {
              levelChanges.push({ level: currentLevel, count: count, months: months });
              currentLevel = performanceLevels[i];
              count = 1;
              months = [monthLabels[i]]; // 重置月份数组
            }
          }
          // 添加最后一个阶段
          levelChanges.push({ level: currentLevel, count: count, months: months });

          // 如果只有一个阶段，直接输出
          if (levelChanges.length === 1) {
            return `始终保持在${currentLevel}阶段`;
          }

          // 构建描述字符串
          const descriptions = levelChanges.map(({ level, count, months }) => {
            // return `${count}个月（${months.join(', ')}）保持在${level}阶段`;
            return `${months.join(', ')}保持在${level}阶段`;
          });

          // 返回完整描述
          return descriptions.join('，');
        },

        async getInfo(sid) {
          return httpService.get(`/students/students/getinfo/${sid}`)
            .then(data => {
              this.studentInfo.scchoolMeaasge = data.scchoolMeaasge
              this.studentInfo.studentclass = data.studentclass
            })
        },

        // 拿取评价信息
        async getEvaluation() {
          await this.getInfo(localStorage.getItem("StudentId"))
          this.studentInfo.StudentId = localStorage.getItem("StudentId")
          this.studentInfo.yearAdmission = localStorage.getItem("yearAdmission")
          this.studentInfo.Yearstem = localStorage.getItem("Yearstem")
          httpService.get('/performancecomparisons/performancecomparisons/list').then(res => {
            if (res.code === 200) {
              // 解析 scoreRanges
              this.evaluation = res.rows;
              this.evaluation.forEach(item => {
                item.scoreRanges = JSON.parse(item.scoreRanges);
              })
              this.getStudnetScore()
            }
          })
          // 获取评价信息
        },
      },
      mounted() {
        this.startSlide()
        // 获取所有抽屉按钮，并为每个按钮添加点击事件监听器 
        const drawerBtns = Array.from(document.querySelectorAll(".drawer-btn"));
        drawerBtns.forEach(btn => {
          btn.addEventListener("click", () => {
            clearInterval(this.intervalID); // 清除定时器 
            this.startSlide(); // 重新启动幻灯片轮播 
          })
        })
        // 获取幻灯片区域 
        const slideSection = document.querySelector("#slide-section");
        // 鼠标移入幻灯片区域时清除定时器 
        slideSection.addEventListener("mouseenter", () => {
          clearInterval(this.intervalID);
        })
        // 鼠标移出幻灯片区域时重新启动幻灯片轮播 
        slideSection.addEventListener("mouseleave", () => {
          this.startSlide();
        })


        /* self数据分析*/
        this.getEvaluation()

      },
    })
  </script>
</body>

</html>